package controllers

import (
	"strconv"
	"time"

	"cashew.com/cashew_api/dtos"
	"cashew.com/cashew_api/models"
	"cashew.com/cashew_api/services"
	"cashew.com/cashew_common/constants"
)

type UserFreeCallsController struct {
	BaseController
}

// 给用户发送免费通话卡
func (c *UserFreeCallsController) SendFreeCalls() {
	req := dtos.SendFreeCallsParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误: ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	userId := req.UserId
	num := req.Num

	// 根据 num 生成 num 个免费通话卡
	ml := []*models.User_free_calls{}
	for i := 0; i < num; i++ {
		ml = append(ml, &models.User_free_calls{
			UserId:     userId,
			Scene:      1,
			CreateTime: time.Now().Unix(),
			ExpireTime: time.Now().Unix() + 3600*24*7,
		})
	}
	err = models.AddUser_free_callsMulti(ml)
	if err != nil {
		c.Error("生成免费通话卡失败: ", err)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	// 查询用户剩余免费通话次数
	remainingNum, err := models.CountAvailableCallsByUserId(userId)
	if err != nil {
		c.Error("查询用户剩余免费通话次数失败: ", err)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	// 发送IM通知
	times := 60
	res, err := models.GetSystem_configsByType(constants.SYS_CONFIG_TYPE_FREE_CALL_USE_TIME)
	if err != nil {
		c.Error("查询系统配置失败: ", err)
		c.Result(constants.ERR_SYS, nil)
		return
	}
	if res != nil {
		times, _ = strconv.Atoi(res.Value)
	}
	_ = services.ImFreeCallChange(req.UserIdStr, req.UserIdStr, num, times, remainingNum)

	// mq 同步用户信息
	go services.SyncUserData(req.UserIdStr, constants.DATA_UPDATED_HAVE_FREE_CARD_UPDATED, nil)

	c.Result(constants.SUCCESS, nil)
}

// 用户剩余有效免费通话次数
func (c *UserFreeCallsController) CountFreeCalls() {
	req := dtos.CountFreeCallsParams{}
	err := dtos.Bind(&req, c.Ctx)

	if err != nil {
		c.Error("参数错误: ", err)
		c.Result(constants.ERR_PARAM, nil)
		return
	}

	userId := req.UserId
	num, err := models.CountAvailableCallsByUserId(userId)
	if err != nil {
		c.Error("查询用户剩余免费通话次数失败: ", err)
		c.Result(constants.ERR_SYS, nil)
		return
	}

	res := dtos.CountFreeCallsRes{
		Num: num,
	}

	c.Result(constants.SUCCESS, res)
}
